package com.demo.service.impl;

import com.demo.common.base.ResultModel;
import com.demo.common.constants.ConstantsCommon;
import com.demo.common.exception.BusinessException;
import com.demo.dao.LoginMapper;
import com.demo.dao.UserInfoMapper;
import com.demo.model.User;
import com.demo.model.UserInfo;
import com.demo.service.LoginService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description: LoginServiceImpl
 * @Author: ChenXueLi
 * @Date: 2018-10-02 15:06
 */
@Service
public class LoginServiceImpl implements LoginService {

    private static Logger logger = Logger.getLogger(LoginServiceImpl.class);

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 用户登录
     * @param account
     * @param password
     * @param resultModel
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel login(String account, String password, ResultModel resultModel, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<User> userList = loginMapper.login(account, password);

        if(userList.size() == 0) {
            throw new BusinessException(-101, "账号或密码错误");
        }
        if(userList.size() > 1){
            throw new BusinessException(-102, "该账号不可用这种方式登录，请尝试其他方式登录");
        }

        User user = userList.get(0);

        UserInfo userInfo = userInfoMapper.getUserInfoById(user.getUserId());

        if(userInfo == null) {
            throw new BusinessException(-103, "用户信息查询失败，请联系管理员");
        }

        request.getSession().setAttribute(ConstantsCommon.LOGIN_INFO, userInfo);

        resultModel.setUserInfo(userInfo);

//        resultModel.setUser(user);

        resultModel.setData(user);
        resultModel.setMessage("登录成功");
        return resultModel;
    }

    /**
     * 用户登出
     * @param resultModel
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    public ResultModel loginOut(ResultModel resultModel, HttpServletRequest request, HttpServletResponse response) throws Exception {
        return null;
    }

}
